import { BaseContext } from 'koa'
import { getManager, Repository } from 'typeorm'
import { User } from '../entity/user'
import { OKBody, FailBody } from '../utils/requests/index'
import { shouldBlock } from '../utils/middleware/parseCtxSession'
import { generateAccessToken } from '../utils/uuid'
import { IsEmail } from '../utils/emailVerification'

export default class UserController {
  public static async getUser(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    const token = ctx.session.token
    // 获取用户信息
    const repo: Repository<User> = getManager().getRepository(User)
    const data: User = await repo.findOne({
      token: token,
    })

    ctx.body = OKBody(data)
  }

  /**
   * 更新用户信息
   * @param ctx Koa Ctx
   */
  public static async updateUser(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))
    try {
      const token = ctx.cookies.token
      // 获取用户信息
      const repo: Repository<User> = getManager().getRepository(User)
      const data: User = await repo.findOne({
        token: token,
      })

      ctx.body = OKBody(data)
    } catch (err) {
      ctx.body = FailBody(err.message)
    }
  }

  /**
   * 创建用户
   * @param ctx KoaContext
   */
  public static async createUser(ctx: BaseContext) {
    // if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))
    try {
      const session = ctx.session
      if (session.isLogin) throw new Error('用户已登录')

      // 获取用户信息
      const repo: Repository<User> = getManager().getRepository(User)

      const body = ctx.request.body
      const user: User = new User()

      if (!body.email) throw new Error('Email字段不能为空')
      if (!body.nickname) throw new Error('nickname字段不能为空')
      if (!IsEmail(body.email)) throw new Error('Email格式有误')

      user.email = body.email
      user.lastLogin = new Date()
      user.nickname = body.nickname || body.email
      user.token = generateAccessToken()

      // 如果存在Email
      const dbUser = await repo.findOne({
        email: user.email,
      })

      // console.log(dbUser)
      if (dbUser) throw Error(`账户: ${user.email} 已存在`)
      // send email with token
      const cratedUser = await repo.save(user)

      // 设置Token
      ctx.cookies.set(
        'token',
        user.token,
      )
      ctx.body = OKBody(cratedUser)
    } catch (err) {
      // 处理Email重复
      ctx.body = FailBody(err.message)
    }
  }
}
